#--*--coding=utf-8--*--
#MaterialCodeGenerator4.py

import sys
import json
import sqlite3
from PySide6.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton, QLabel, QComboBox, QLineEdit, QHBoxLayout, QMessageBox
from PySide6.QtCore import Qt
from PySide6.QtGui import QClipboard

import chardet

"""
        # 从JSON文件加载编码规则
        with open('rules.json', 'rb') as f:
            raw_data = f.read()
            result = chardet.detect(raw_data)
            self.encoding = result['encoding']
            
        with open('rules.json', 'r', encoding=self.encoding) as f:
            self.rules = json.load(f)

"""

import sys
import json
import chardet
import sqlite3
from PySide6.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton, QLabel, QComboBox, QLineEdit, QHBoxLayout, QMessageBox
from PySide6.QtCore import Qt
from PySide6.QtGui import QClipboard

# 加载规则
def load_rules_from_json(file_path):
    # 读取文件内容以检测编码
    with open(file_path, 'rb') as f:
        raw_data = f.read()
        result = chardet.detect(raw_data)
        encoding = result['encoding']
    
    # 使用检测到的编码打开文件并加载JSON数据
    with open(file_path, 'r', encoding=encoding) as file:
        return json.load(file)

def load_rules_from_db(db_path):
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()
    rules = {}
    
    # 读取第1组规则
    cursor.execute("SELECT name, code FROM part1")
    rules['part1'] = {name: code for name, code in cursor.fetchall()}
    
    # 读取第2组规则
    cursor.execute("SELECT name, code FROM part2")
    rules['part2'] = {name: code for name, code in cursor.fetchall()}
    
    # 读取第3组规则
    cursor.execute("SELECT name, code FROM part3")
    rules['part3'] = {name: code for name, code in cursor.fetchall()}
    
    conn.close()
    return rules

class MaterialCodeGenerator(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.layout = QVBoxLayout()
        self.setLayout(self.layout)

        # 初始化规则
        self.rules = load_rules_from_json('rules1.json')

        # 初始化下拉列表和搜索框
        self.initDropdownsAndSearchBoxes()

        # 增加/删除按钮
        self.add_remove_buttons_layout = QHBoxLayout()
        self.addButton = QPushButton("增加一组")
        self.removeButton = QPushButton("删除一组")
        self.add_remove_buttons_layout.addWidget(self.addButton)
        self.add_remove_buttons_layout.addWidget(self.removeButton)
        self.layout.addLayout(self.add_remove_buttons_layout)

        # 连接信号与槽
        self.addButton.clicked.connect(self.addDropdownGroup)
        self.removeButton.clicked.connect(self.removeDropdownGroup)

        # 显示生成的编码
        self.codeLabel = QLabel("生成的编码:")
        self.layout.addWidget(self.codeLabel)

    def initDropdownsAndSearchBoxes(self):
        self.dropdownGroups = []
        self.searchBoxes = []

        # 初始添加三组
        for _ in range(3):
            self.addDropdownGroup()

    def addDropdownGroup(self):
        group_layout = QHBoxLayout()
        comboBox = QComboBox()
        searchBox = QLineEdit()
        searchBox.setPlaceholderText("搜索...")

        # 填充下拉列表
        if len(self.dropdownGroups) == 0:
            comboBox.addItems(list(self.rules['part1'].keys()))
        elif len(self.dropdownGroups) == 1:
            comboBox.addItems(list(self.rules['part2'].keys()))
        else:
            comboBox.addItems(list(self.rules['part3'].keys()))

        # 连接搜索框文本变化事件
        searchBox.textChanged.connect(lambda text, cb=comboBox: self.filterComboBox(text, cb))

        group_layout.addWidget(comboBox)
        group_layout.addWidget(searchBox)
        self.layout.addLayout(group_layout)

        self.dropdownGroups.append(comboBox)
        self.searchBoxes.append(searchBox)

    def removeDropdownGroup(self):
        if self.dropdownGroups:
            last_group_layout = self.layout.takeAt(self.layout.count() - 2).layout()
            while last_group_layout.count():
                widget = last_group_layout.takeAt(0).widget()
                if widget:
                    widget.deleteLater()
            self.dropdownGroups.pop()
            self.searchBoxes.pop()

    def filterComboBox(self, text, comboBox):
        current_text = comboBox.currentText()
        comboBox.clear()
        items = [comboBox.itemText(i) for i in range(comboBox.count())]
        filtered_items = [item for item in items if text.lower() in item.lower()]
        comboBox.addItems(filtered_items)
        comboBox.setCurrentText(current_text)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = MaterialCodeGenerator()
    ex.show()
    sys.exit(app.exec())



